// 主平台通信桥
import { CommandCenterInstance as cmd } from './commandCenter';
import { switchTheme } from '../utils/tools';

export default class Bridge {
  static agentId = null;
  static token = null;
  static _initialized = false;
  /**
   * 初始化通信桥，监听主平台指令
   */
  static init() {
    if (this._initialized) return;
    this._initialized = true;
    console.log('[bridge] 初始化通信桥');
    cmd.unlistenIframeMessage();
    cmd.listenIframeMessage();

    // 注册平台级别的通用指令
    register();
  };
  static destroy = () => {
    if (!this._initialized) return;
    this._initialized = false;
    cmd.unlistenIframeMessage();
  };
  static setAgentId = (agentId) => {
    this.agentId = agentId;
  }
  static setToken = (token) => {
    this.token = token;
  }
  /**
   * 发送指令到主平台
   * @param {string} command 指令名称
   * @param {object} args 传递参数
   * @param {object} [options] 可选项，如 id、source
   */
  static send = (command, args = {}, options = {}) => {
    const safeData = JSON.parse(JSON.stringify(args));
    const message = {
      command,
      args: {
        ...safeData,
        agentId: this.agentId,
      },
      stream: options.stream || false,
      id: options.id || this.agentId || `msg-${Date.now()}`,
      source: options.source || 'agent-miniapp',
      token: this.token,
    };
    cmd.sendToParent(message);
  };
  static on = (command, fn) => {
    cmd.on(command, fn);
  };
  static off = (command, fn) => {
    cmd.off(command, fn);
  };
  static once = (command, fn) => {
    cmd.once(command, fn);
  };
  static receive = (command, fn) => {
    if (!commandHandlers.has(command)) {
      commandHandlers.set(command, []);
    }
    commandHandlers.get(command).push(fn);
  };
  static removeReceive = (command, fn) => {
    if (!commandHandlers.has(command)) return;
    const handlers = commandHandlers.get(command);
    const index = handlers.indexOf(fn);
    if (index !== -1) {
      handlers.splice(index, 1);
    }
  }
  // 模拟post请求
  static post = (command, args = {}, options = {}) => {
    return new Promise((resolve, reject) => {
      this.send(command, args, options);
      this.once(command, (res) => {
        if (res.status === 'SUCCEEDED') {
          resolve(res.data);
        } else {
          reject(res.message);
        }
      });
    });
  }
}

const commandHandlers = new Map();
// ✅ 通用注册方法，统一默认处理和自定义扩展逻辑
const registerCommand = (command, defaultHandler) => {
  cmd.register(command, async (args, ctx) => {
    const handlers = commandHandlers.get(command);
    if (handlers && handlers.length > 0) {
      for (const fn of handlers) {
        try {
          await fn(args, ctx);
        } catch (e) {
          console.warn(`[bridge] Error in custom handler for "${command}":`, e);
        }
      }
    } else {
      await defaultHandler?.(args, ctx);
    }
  });
};

// ✅ 批量注册
const register = () => {
  registerCommand('ping', async (args, ctx) => {
    ctx.reply({
      status: 'SUCCEEDED',
      message: 'pong',
      data: '平台平台，我是Agent！over！',
      args,
    });
  });
  registerCommand('agent.themeSet', async (args, ctx) => {
    const themeName = args?.theme;
    if (!themeName) {
      ctx.reply({
        status: 'FAILED',
        message: '主题名称不能为空',
        data: '主题名称不能为空',
      });
    }
    switchTheme(themeName);
    console.log(`[bridge] 主题已改变为${themeName}`);
    ctx.reply({
      status: 'SUCCEEDED',
      message: `主题已改变为${themeName}`,
      data: `主题已改变为${themeName}`,
    });
  });

  registerCommand('workspace.update', async (args, ctx) => {
    const data = args?.data && typeof args.data === 'object' ? args.data : {};
    ctx.reply({ status: 'SUCCEEDED', message: 'Hello World!' });
  });
  registerCommand('agent.update', async (args, ctx) => {
    const data = args?.data && typeof args.data === 'object' ? args.data : {};
    ctx.reply({ status: 'SUCCEEDED', message: 'Hello World!' });
  });

  // 可继续扩展更多平台指令...
};